package com.ymy.spring.cloud.alibaba.sentinel.persistent.exception.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 全局 {@link BlockExceptionHandler} 处理器
 *
 * @author Ringo
 * @date 2021/10/8 11:08
 */
@Component
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {

    @Value("${block.exception.handler.default-tip-message}")
    private String defaultMessage;


    @Value("${block.exception.handler.system-tip-message}")
    private String systemMessage;

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        // Return 429 (Too Many Requests) by default.
        response.setStatus(429);
        response.setContentType("application/json;charset=UTF-8");

        String msg = defaultMessage;

        if (e instanceof SystemBlockException) {
            msg = systemMessage;
        }

        PrintWriter out = response.getWriter();
        out.print(msg);
        out.flush();
        out.close();
    }
}
